package com.gyl.aspect.utils;

import java.lang.reflect.Field;

/**
 * 映射工具类
 * @description
 */
public class ReflectUtil {

	/**
	 * @description 把一个bean转换成json字符串的格式  
	 * @author gyl
	 */
	public static String toJsonStringPattern(Class<?> clazz) {
		StringBuilder result = new StringBuilder("{");
		Field[] fields = clazz.getDeclaredFields();
		
		for (Field item : fields) {
			result.append("\"").append(item.getName()).append("\": ").append("\"\",");
		}
		return result.substring(0, result.length() - 1) + "}";
	}
	
	/**
	 * @description 拿到字段的值
	 * @author gyl
	 */
	public static Object getFieldValue(Field field, Object obj) throws Exception {
		field.setAccessible(true);
		Object result = field.get(obj);
		field.setAccessible(false);
		return result;
	}
	
	/**
	 * @description 拿到一个对象上一个字段的值，包括其父类
	 * @author gyl
	 */
	public static Object getFieldValue(Class<?> clazz, Object obj, String fieldName) throws Exception{
		// 根据字段名, 拿到字段, 
		Class<?> superClazz = clazz;
		Field field = null;
		while(null == field && !Object.class.equals(superClazz)) {
			try {
				field = superClazz.getDeclaredField(fieldName);
			} catch (Exception e) {
				// 本类里找不到该属性, 就去父类里去找
				try {
					field = obj.getClass().getDeclaredField(fieldName);
				}catch (Exception e1){

				}
			}
			superClazz = superClazz.getSuperclass(); 
		}
		if(field == null) {
			throw new IllegalArgumentException("找不到指定的字段：" + fieldName);
		}
		return getFieldValue(field, obj);
	}

}